//
//  UnStartEventController.m
//  Runone
//
//  Created by ekkaLyn on 2017/3/14.
//  Copyright © 2017年 runone. All rights reserved.
//

#import "UnStartEventController.h"
#import "UnStartEventView.h"
#import "ChooseTimeView.h"
#import "ChoosePileNOView.h"
#import "ChooseDirectionView.h"
#import "PhotoesScrollView.h"
#import "InProgressPicAndVideoView.h"
#import "InProgressConstructPositionView.h"
#import "SDAutoLayout.h"
#import "RequestHelper.h"
#import "EventDetailModel.h"
#import "MJExtension.h"
#import "SVProgressHUD.h"
#import "ROImagePickViewController.h"
#import "AJPhotoPickerViewController.h"
#import "AJPhotoBrowserViewController.h"
#import "LittleVideoViewController.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "BCNetAPIClient.h"
#import "HighwayMergeRoadRecordModel.h"
#import "DateViewController.h"
#import "DropDownBackView.h"
#import "EventDetailModel.h"
#import "AppDelegate.h"
#import "HighWayRoadRecordDirectionInfoModel.h"
#import "DrowDownViewController.h"
#import "PileInfo.h"
#import "ConstructionEventDetailInfo.h"
#import "RODateHelper.h"
#import "EventDealList.h"
#import "ParModel.h"
#import "EKDateTimePickerView.h"
#import "UIColor+Addition.h"
#import "NSDate+Extension.h"

@interface UnStartEventController ()<UIScrollViewDelegate, LittleVideoDelegate,AJPhotoPickerProtocol, AJPhotoBrowserDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate, UIAlertViewDelegate, UIPopoverPresentationControllerDelegate>{
    AVPlayer *_player;
    AVPlayerItem *_playItem;
    AVPlayerLayer *_playerLayer;
    AVPlayerLayer *_fullPlayer;
    BOOL _isPlaying;
}
@property (nonatomic, strong) UIScrollView                    *scroollView;
@property (nonatomic, strong) UIView                          *wrapperView;
@property (nonatomic, strong) UIView                          *containerV;        // 容器
@property (nonatomic, strong) UnStartEventView                *constructV;        // 施工单位
@property (nonatomic, strong) UnStartEventView                *personInChargeV;   // 现场负责人
@property (nonatomic, strong) UnStartEventView                *contacterV;        // 联系人
@property (nonatomic, strong) ChooseTimeView                  *planBeginTimeV;    // 计划开始时间
@property (nonatomic, strong) ChooseTimeView                  *planEndTimeV;      // 计划结束时间
@property (nonatomic, strong) InProgressConstructPositionView *postionV;          //施工地点
@property (nonatomic, strong) ChoosePileNOView                *beginPileNOV;      //开始桩号
@property (nonatomic, strong) ChoosePileNOView                *endPileNOV;        //结束桩号
@property (nonatomic, strong) ChooseDirectionView             *vehicleDirectionV; //行车方向
@property (nonatomic, strong) UnStartEventView                *constructProjectV; //施工项目
@property (nonatomic, strong) UnStartEventView                *constructDesV;     //施工描述
@property (nonatomic, strong) PhotoesScrollView               *photoesV;          //选中的图片的view
@property (nonatomic, strong) InProgressPicAndVideoView       *picAndVideoV;      // 图片和视频按钮
//@property (nonatomic, strong) UIScrollView                    *imageScrollV;      //图片
@property (nonatomic, strong) UIView                          *videoView;         //小视频
@property (nonatomic, strong) NSURL                           *videoUrl;
@property (nonatomic, strong) EventDetailModel                *Model; //请求返回的事件模型
@property (nonatomic, strong) NSMutableArray                  *selectPhoteArray; //选中的图片数组
@property (strong, nonatomic) DateViewController *dateVC;
@property (strong, nonatomic) DropDownBackView *backView;             //下拉框

// **************************************** -数组- ****************************************
@property (nonatomic, strong) NSMutableArray *lineArray;//主线 南北连接线
@property (nonatomic, strong) NSArray *isMainLineArray;//是否是主线

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *dealTVHeight;

@property (nonatomic, strong) NSMutableArray *roadDirectionArray;

@property (nonatomic, strong) HighwayMergeRoadRecordModel *currentRoadModel;//当前模型

@property (nonatomic, assign) NSInteger roadIndex;

@property(nonatomic, strong) LittleVideoViewController *littleVideoVC;//拍摄小视频界面
@property (nonatomic, strong) NSMutableArray *stationArray;
@property (nonatomic, strong) StationModel *stationModel; //当前选中的收费站
@property (nonatomic, strong) NSDate *lastScrollDate;// 上一次滚动的时间

@end

@implementation UnStartEventController
#pragma mark - lazy load
- (UIScrollView *)scroollView {
    if (!_scroollView) {
        _scroollView = [UIScrollView new];
        _scroollView.delegate = self;
        _scroollView.bounces  = NO;
        [self.view addSubview:_scroollView];
        _scroollView.showsVerticalScrollIndicator = YES;
        _scroollView.showsHorizontalScrollIndicator = NO;
        _scroollView.sd_layout
        .topSpaceToView(self.view, 0)
        .leftSpaceToView(self.view, 0)
        .rightSpaceToView(self.view, 0)
        .bottomSpaceToView(self.view, 0);
    }
    return _scroollView;
}
- (PhotoesScrollView *)photoesV {
    if (!_photoesV) {
        PhotoesScrollView *photoesV = [[PhotoesScrollView alloc] init];
        _photoesV = photoesV;
        [self.containerV addSubview:_photoesV];
        self.photoesV.sd_layout
        .widthIs([UIScreen mainScreen].bounds.size.width - 20)
        .heightIs(100)
        .topSpaceToView(self.constructDesV, 10)
        .centerXEqualToView(self.containerV)
        ;
    }
    return _photoesV;
}
- (UIView *)videoView {
    if (!_videoView) {
        UIView *newView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width - 20, 100)];
        _videoView = newView;
        newView.backgroundColor = [UIColor whiteColor];
        [self.containerV addSubview:_videoView];
    }
    return _videoView;
}
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self configNaviABar];
    [self configUI];
    self.wrapperView.sd_layout
    .leftEqualToView(self.scroollView)
    .rightEqualToView(self.scroollView)
    .topEqualToView(self.scroollView);
    [self setConfig];
    [self setUpArray] ;
    [self requestData];
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    for (StationModel *sModel  in myDelegate.AllTollStationArray) {
        [_stationArray addObject:sModel.TollStationName];
    }
    [self configDropDownData];
   
}
- (void) setConfig{
    _Model    = [[EventDetailModel alloc] init];
    _backView = [[DropDownBackView alloc] init];
}
#pragma mark -下拉
- (void) configDropDownData {
    // 主线 南北
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    for (HighwayMergeRoadRecordModel *moel in myDelegate.HighWayRoadArray) {
        [_lineArray addObject:moel.RoadName];
    }
    [_lineArray addObject:@"收费站"];
    _isMainLineArray = @[@"主线",@"非主线"];
}

- (void) refreshBeginAndEndPileNO:(StationModel *)model {
    NSString *b                 = [NSString stringWithFormat:@"%@",model.PileNo];
    NSString *begin             = [b stringByReplacingOccurrencesOfString:@"K" withString:@" "];
    NSString *beginDistance     = [NSString stringWithFormat:@"%ld",(long)model.PileDistance];
       if ([_Model.EventBaseInfo.RoadUID isEqualToString:@"8dd13d88-cb02-4471-876b-1dfe39419ee6"]) {
        NSString *kBeginStr = [NSString stringWithFormat:@" %@",begin];
        [self.beginPileNOV setMiddelString:kBeginStr rightString:beginDistance];
        [self.endPileNOV setMiddelString:kBeginStr rightString:beginDistance];
        
    } else {
        NSString *lkBeginStr = [NSString stringWithFormat:@"LK %@",begin];
        [self.beginPileNOV setMiddelString:lkBeginStr rightString:beginDistance];
        [self.endPileNOV setMiddelString:lkBeginStr rightString:beginDistance];
    }

}

- (void)changeMainLineOrStation:(UIButton *)sender {
    __weak __typeof(self)weakSelf = self;
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    DrowDownViewController *directionVC = [[DrowDownViewController alloc]init];
    directionVC.view.width              = sender.width ;
    directionVC.dataArray               = _lineArray;
    directionVC.view.height             = 44 * (_lineArray.count);
    _backView.contentController         = directionVC;
    directionVC.indexClick              = ^(NSInteger tag, NSString *str){
        weakSelf.postionV.middelLabel.text = str;
        if (tag == _lineArray.count - 1) { //收费站
            //            AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            StationModel *sModel = myDelegate.AllTollStationArray[0];
            _stationModel = sModel;
            for (HighwayMergeRoadRecordModel *model in myDelegate.HighWayRoadArray) {
                if ([model.RoadUID isEqualToString:sModel.RoadUID]) {
                    _currentRoadModel = model;
                }
            }
            weakSelf.postionV.middelLabel.text = str;
            weakSelf.postionV.rightLabel.text  = sModel.TollStationName  ;
            [weakSelf refreshBeginAndEndPileNO:sModel];
            [self setTransDirection];
            
        }else {
            _currentRoadModel               = myDelegate.HighWayRoadArray[tag];
            [self setIsMAinline];
            self.beginPileNOV.midTextField.text   = @"";
            self.beginPileNOV.rightTextField.text = @"";
            self.endPileNOV.midTextField.text     = @"";
            self.endPileNOV.rightTextField.text   = @"";
            [self setKOrLKLabel];
//            [self refreshLinePileNO];
        }
        [_backView dismiss];
        [self refreshDirectionArray];
        [self setTransDirection];
    };
    [_backView showFrom:self.postionV.middelBtn];
}
- (void)changeRampOrStationName:(UIButton *)sender {
    //    NSLog(@"是否是主线");
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    __weak __typeof(self)weakSelf = self;
    if ([self.postionV.middelLabel.text isEqualToString:@"收费站"]) { //如果是收费站
        DrowDownViewController *stationList = [[DrowDownViewController alloc] init];
        stationList.view.width              = sender.width + 10 ;
        stationList.dataArray               = _stationArray;
        stationList.view.height             = 44 * 5;
        _backView.contentController         = stationList;
        stationList.indexClick              = ^(NSInteger tag, NSString *str){
            self.postionV.rightLabel.text = str;
            _stationModel    = myDelegate.AllTollStationArray[tag];
            for (HighwayMergeRoadRecordModel *roadModel in myDelegate.HighWayRoadArray) {
                if ([roadModel.RoadUID isEqualToString:_stationModel.RoadUID]) {
                    _currentRoadModel = roadModel;
                }
            }
            [self setKOrLKLabel];
            [self refreshPileNO:tag];
            [self refreshDirectionArray];
            [weakSelf.backView dismiss];
        };
        [_backView showFrom:sender];
        
    }else{
        DrowDownViewController *directionVC = [[DrowDownViewController alloc]init];
        directionVC.view.width              = sender.width + 10 ;
        directionVC.dataArray               = _isMainLineArray;
        directionVC.view.height             = 44 * (_isMainLineArray.count);
        _backView.contentController         = directionVC;
        directionVC.indexClick              = ^(NSInteger tag, NSString *str){
          //  weakSelf.isMianLine.text        = [NSString stringWithFormat:@"%@",str];
            self.postionV.rightLabel.text = str;
            [weakSelf.backView dismiss];
        };
        [_backView showFrom:sender];
    }
}
- (void)planBeginTimeBtnClick:(UIButton *)sender {
    [self setUpDatePicker:self.planBeginTimeV.timeChooseBtn];
}

- (void) setUpDatePicker:(UIButton *)sender {
    
    EKDateTimePickerView *datepicker = [[EKDateTimePickerView alloc]initWithDatePosition:EKDatePositionMiddel CompleteBlock:^(NSDate *startDate) {
        _lastScrollDate = startDate;
        NSString *dateStr = [startDate stringWithOutTimeWithFormat:@"yyyy-MM-dd HH:mm:ss"];
        [sender setTitle:dateStr forState:UIControlStateNormal];
    }];
    datepicker.datePickerStyle = EKDateStyleShowYearMonthDayHourMinute;
    datepicker.themeColor      = [UIColor colorWithHexString:@"38b1dc"];
    if (sender.currentTitle != nil) {
        _lastScrollDate = nil;
        [datepicker scrollToSepicefyDate:[RODateHelper dateWithOutTimeZoneFromString:sender.currentTitle withFormat:nil] animated:NO];
    }
    
    if (_lastScrollDate != nil) {
        [datepicker scrollToSepicefyDate:_lastScrollDate animated:NO];
    }
    [datepicker show];
}


- (void)planEndTimeBtnClick:(UIButton *)sender {
    [self setUpDatePicker:self.planEndTimeV.timeChooseBtn];
}
- (void)roadDirectionBtnClick:(UIButton *)sender {
    [_roadDirectionArray removeAllObjects];
    [self refreshDirectionArray];
    __weak __typeof(self)weakSelf       = self;
    DrowDownViewController *directionVC = [[DrowDownViewController alloc]init];
    directionVC.view.width              = sender.width;
    directionVC.dataArray               = _roadDirectionArray;
    directionVC.view.height             = 44 * (_roadDirectionArray.count) + 10;
    _backView.contentController         = directionVC;
    directionVC.indexClick              = ^(NSInteger tag, NSString *str){
        [weakSelf.vehicleDirectionV setContentString:str];
        _roadIndex  = tag + 1;
        [_backView dismiss];
    };
    [_backView showFrom:sender];
}

-(void)datePick {
    _dateVC=[[DateViewController alloc] init];
    _dateVC.modalPresentationStyle=UIModalPresentationPopover;
    _dateVC.popoverPresentationController.sourceView=self.view;
    _dateVC.popoverPresentationController.sourceRect=CGRectMake(self.view.center.x-56, self.view.center.y, 0, 0);
    _dateVC.popoverPresentationController.permittedArrowDirections=NO;
    _dateVC.popoverPresentationController.delegate = self;
}


- (void) setKOrLKLabel {
    if ([_currentRoadModel.RoadUID isEqualToString:@"8dd13d88-cb02-4471-876b-1dfe39419ee6"]) {
        UILabel *lab1      = [[UILabel alloc] init];
        lab1.text                 = @"K";
        lab1.frame                = CGRectMake(0, 0, 15, 10);
        lab1.textAlignment        = NSTextAlignmentCenter;
        self.beginPileNOV.midTextField.leftView     = lab1;
        self.beginPileNOV.midTextField.leftViewMode = UITextFieldViewModeAlways;
        
        UILabel *lab2      = [[UILabel alloc] init];
        lab2.text               = @"K";
        lab2.frame              = CGRectMake(0, 0, 15, 10);
        lab2.textAlignment      = NSTextAlignmentCenter;
        self.endPileNOV.midTextField.leftView     = lab2;
        self.endPileNOV.midTextField.leftViewMode = UITextFieldViewModeAlways;
        
    } else {
        UILabel *lab1      = [[UILabel alloc] init];
        lab1.font          = [UIFont boldSystemFontOfSize:15];
        lab1.text                 = @"LK";
        lab1.frame                = CGRectMake(0, 0, 25, 10);
        lab1.textAlignment        = NSTextAlignmentCenter;
        self.beginPileNOV.midTextField.leftView     = lab1;
        self.beginPileNOV.midTextField.leftViewMode = UITextFieldViewModeAlways;
        
        UILabel *lab2      = [[UILabel alloc] init];
        lab2.font          = [UIFont boldSystemFontOfSize:15];
        lab2.text               = @"LK";
        lab2.frame              = CGRectMake(0, 0, 25, 10);
        lab2.textAlignment      = NSTextAlignmentCenter;
        self.endPileNOV.midTextField.leftView     = lab2;
        self.endPileNOV.midTextField.leftViewMode = UITextFieldViewModeAlways;
    }
}

- (void) refreshPileNO:(NSInteger )tag {
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    StationModel *model = myDelegate.AllTollStationArray[tag];
    NSInteger length    = model.PileNo.length;
    self.beginPileNOV.midTextField.text = [model.PileNo substringWithRange:NSMakeRange(1, length - 1)];
    self.beginPileNOV.rightTextField.text = [NSString stringWithFormat:@"%ld",(long)model.PileDistance];
    self.endPileNOV.midTextField.text = [model.PileNo substringWithRange:NSMakeRange(1, length - 1)];
    self.endPileNOV.rightTextField.text = [NSString stringWithFormat:@"%ld",(long)model.PileDistance];
}

- (void) refreshDirectionArray {
    for (HighWayRoadRecordDirectionInfoModel *directionModel in _currentRoadModel.highWayRoadDirectionList) {
        [_roadDirectionArray addObject:directionModel.DirectionDescription];
    }
}

#pragma mark -联动方向
- (void) setTransDirection {
    [_roadDirectionArray  removeAllObjects];
    for (HighWayRoadRecordDirectionInfoModel *directModel in _currentRoadModel.highWayRoadDirectionList) {
        [_roadDirectionArray addObject:directModel.DirectionDescription];
    }

    self.vehicleDirectionV.directionLabel.text = _roadDirectionArray[0];
}

- (void) setIsMAinline {
    self.postionV.rightLabel.text = @"主线";
}

#pragma mark -默认的数据
- (void) configCurrentData {
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    for (HighwayMergeRoadRecordModel *highModel in myDelegate.HighWayRoadArray) {
        if ([_reportModel.RoadUID isEqualToString:highModel.RoadUID]) {
            _currentRoadModel = highModel;//获取当前的道路模型
            [self configLineTF];
        }
    }
    //配置默认的道路方向数组
    for (HighWayRoadRecordDirectionInfoModel *model in _currentRoadModel.highWayRoadDirectionList) {
        [_roadDirectionArray addObject:model.DirectionDescription];
    }
}

- (void) configLineTF {
//    _mainLineTF.text = _currentRoadModel.RoadName;
    [self.postionV.middelBtn setTitle:_currentRoadModel.RoadName forState:UIControlStateNormal];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

#pragma mark -  navagationBar
- (void) configNaviABar {
    UIButton *commitBtn = [[UIButton alloc] init];
    [commitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [commitBtn setBackgroundImage:[UIImage imageNamed:@"event_check_commit"] forState:UIControlStateNormal];
    commitBtn.frame         = CGRectMake(0, 0, 40, 20);
    [commitBtn addTarget:self action:@selector(commitBtnClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *commit = [[UIBarButtonItem alloc] initWithCustomView:commitBtn];
    
    UIButton *cancleBtn = [[UIButton alloc] init];
    [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancleBtn.frame         = CGRectMake(0, 0, 40, 20);
    [cancleBtn addTarget:self action:@selector(cancleBtnClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *cancle = [[UIBarButtonItem alloc] initWithCustomView:cancleBtn];
    
    self.navigationItem.rightBarButtonItems = @[commit, cancle];
    //主标题
    UILabel *titleL               = [[UILabel alloc] init];
    titleL.text                   = @"未开始事件";
    titleL.frame                  = CGRectMake(0, 0, 150, 30);
    titleL.textAlignment          = NSTextAlignmentCenter;
    titleL.textColor              = [UIColor whiteColor];
    self.navigationItem.titleView = titleL;
}
#pragma mark - UI
- (void) configUI {
    self.view.backgroundColor = [UIColor colorWithRed:226.0 / 255 green:230.0 / 255 blue:240.0 / 255 alpha:1];
    self.wrapperView = [UIView new];
    self.wrapperView.backgroundColor = [UIColor colorWithRed:239.0 / 255 green:239.0 / 255 blue:249.0 / 255 alpha:0.8];
    [self.scroollView addSubview:self.wrapperView];
    [self configContainerV];
    [self configConstructV];
    [self configPersonInCharge];
    [self configContacterV];
    [self configPlanBeginTimeV];
    [self configPlanEndTimeV];
    [self configConstructPositionV];
    [self configBeginPileNOV];
    [self configEndPileNOV];
    [self configConstructDirectionV];
    [self configConstructProjectV];
    [self configConstructDescriptionV];
    [self configPicAndVideoView];
    self.wrapperView.sd_layout
    .leftEqualToView(self.scroollView)
    .rightEqualToView(self.scroollView)
    .topEqualToView(self.scroollView)
    ;
    [self.containerV setupAutoHeightWithBottomView:self.constructDesV bottomMargin:10]   ;
    [self.wrapperView setupAutoHeightWithBottomView:self.picAndVideoV bottomMargin:10]   ;
    [self.scroollView setupAutoContentSizeWithBottomView:self.wrapperView bottomMargin:0];
}
- (void) configContainerV {
    self.containerV = [[UIView alloc] init];
    [self.wrapperView addSubview:self.containerV];
    self.containerV.sd_layout
    .leftSpaceToView(self.wrapperView, 0)
    .rightSpaceToView(self.wrapperView, 0)
    .topSpaceToView(self.wrapperView, 0)
    .autoHeightRatio(0)
    ;
}
- (void) configConstructV {
    self.constructV = [[UnStartEventView alloc] initWithDefalutHeight:40.0 title:@"施 工 单 位:"];
    [self.containerV addSubview:self.constructV];
    self.constructV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .topSpaceToView(self.containerV, 0)
    .rightSpaceToView(self.containerV, 0)
    .autoHeightRatio(0)
    ;
}
- (void) configPersonInCharge {
    self.personInChargeV = [[UnStartEventView alloc] initWithDefalutHeight:40.0 title:@"现 场 负 责 人:"];
    [self.containerV addSubview:self.personInChargeV];
    self.personInChargeV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .topSpaceToView(self.constructV, 0)
    .rightSpaceToView(self.containerV, 0)
    .autoHeightRatio(0)
    ;
}
- (void) configContacterV {
    self.contacterV = [[UnStartEventView alloc] initWithDefalutHeight:40.0 title:@"联  系  人:"] ;
    [self.containerV addSubview:self.contacterV];
    self.contacterV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .topSpaceToView(self.personInChargeV, 0)
    .rightSpaceToView(self.containerV, 0)
    .autoHeightRatio(0)
    ;
}
- (void) configPlanBeginTimeV {
    self.planBeginTimeV = [[ChooseTimeView alloc] initWithDefalutHeight:40.0 title:@"计划开始时间:"];
    [self.planBeginTimeV.timeChooseBtn addTarget:self action:@selector(planBeginTimeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.containerV addSubview:self.planBeginTimeV];
    self.planBeginTimeV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .topSpaceToView(self.contacterV, 0)
    .rightSpaceToView(self.containerV, 0)
    .autoHeightRatio(0)
    ;
}
- (void) configPlanEndTimeV {
    self.planEndTimeV = [[ChooseTimeView alloc] initWithDefalutHeight:40.0 title:@"计划结束时间:"];
    [self.planEndTimeV.timeChooseBtn addTarget:self action:@selector(planEndTimeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.containerV addSubview:self.planEndTimeV];
    self.planEndTimeV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .topSpaceToView(self.planBeginTimeV, 0)
    .rightSpaceToView(self.containerV, 0)
    .autoHeightRatio(0)
    ;
}
- (void) configConstructPositionV {
    self.postionV = [[InProgressConstructPositionView alloc] initWithDefalutHeight:40.0 title:@"施 工 地 点:" isCanTouch:YES];
    [self.containerV addSubview:self.postionV];
    [self.postionV.middelBtn addTarget:self action:@selector(changeMainLineOrStation:) forControlEvents:UIControlEventTouchUpInside];
    [self.postionV.rightBtn addTarget:self action:@selector(changeRampOrStationName:) forControlEvents:UIControlEventTouchUpInside];
    self.postionV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .rightSpaceToView(self.containerV, 0)
    .topSpaceToView(self.planEndTimeV,0)
    .autoHeightRatio(0)
    ;
}
- (void) configBeginPileNOV {
    self.beginPileNOV = [[ChoosePileNOView alloc]initWithDefalutHeight:40 titleString:@"开 始 桩 号:"];
    self.beginPileNOV.midTextField.keyboardType = UIKeyboardTypePhonePad;
    self.endPileNOV.rightTextField.keyboardType = UIKeyboardTypePhonePad;
    [self.containerV addSubview:self.beginPileNOV];
    self.beginPileNOV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .rightSpaceToView(self.containerV, 0)
    .topSpaceToView(self.postionV,0)
    .autoHeightRatio(0)
    ;
}

- (void) configEndPileNOV {
    self.endPileNOV = [[ChoosePileNOView alloc]initWithDefalutHeight:40 titleString:@"结 束 桩 号:"];
    self.endPileNOV.midTextField.keyboardType = UIKeyboardTypePhonePad;
    self.endPileNOV.rightTextField.keyboardType = UIKeyboardTypePhonePad;
    [self.containerV addSubview:self.endPileNOV];
    self.endPileNOV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .rightSpaceToView(self.containerV, 0)
    .topSpaceToView(self.beginPileNOV,0)
    .autoHeightRatio(0)
    ;
}

- (void) configConstructDirectionV {
    self.vehicleDirectionV = [[ChooseDirectionView alloc] initWithDefalutHeight:40.0 title:@"行 车 方 向:"];
    [self.vehicleDirectionV.chooseDirectBtn addTarget:self action:@selector(roadDirectionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.containerV addSubview:self.vehicleDirectionV];
    self.vehicleDirectionV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .rightSpaceToView(self.containerV, 0)
    .topSpaceToView(self.endPileNOV,0)
    .autoHeightRatio(0)
    ;
}
- (void) configConstructProjectV {
    self.constructProjectV = [[UnStartEventView alloc] initWithDefalutHeight:40.0 title:@"施 工 项 目:"];
    [self.containerV addSubview:self.constructProjectV];
    self.constructProjectV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .rightSpaceToView(self.containerV, 0)
    .topSpaceToView(self.vehicleDirectionV,0)
    .autoHeightRatio(0)
    ;
}
- (void) configConstructDescriptionV {
    self.constructDesV = [[UnStartEventView alloc] initWithDefalutHeight:40.0 title:@"施 工 描 述:" ];
    [self.containerV addSubview:self.constructDesV];
    self.constructDesV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .rightSpaceToView(self.containerV, 0)
    .topSpaceToView(self.constructProjectV,0)
    .autoHeightRatio(0)
    ;
}
- (void) configPicAndVideoView {
    self.picAndVideoV = [[InProgressPicAndVideoView alloc] initWithDefalutHeight:40.0];
    [self.wrapperView addSubview:self.picAndVideoV];
    [self.picAndVideoV.picturesBtn addTarget:self action:@selector(photoesBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.picAndVideoV.videoBtn addTarget:self action:@selector(videoBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.picAndVideoV.sd_layout
    .leftSpaceToView(self.wrapperView, 0)
    .rightSpaceToView(self.wrapperView, 0)
    .topSpaceToView(self.containerV, 10)
    .autoHeightRatio(0)
    ;
}
#pragma mark - 导航栏按钮点击
- (void) commitBtnClick {
    NSLog(@"提交");
    if (self.constructV.desTextV.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"施工单位不能为空"];
        return;
    }
    
    if (self.personInChargeV.desTextV.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"现场负责人不能为空"];
        return;
    }
    
    if (self.contacterV.desTextV.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"联系电话不能为空"];
        return;
    }
    
    if (self.contacterV.desTextV.text.length > 11) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确电话号码"];
        return;
    }
    
    if (self.planBeginTimeV.timeChooseBtn.currentTitle.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"计划开始时间不能为空"];
        return;
    }
    
    if (self.planEndTimeV.timeChooseBtn.currentTitle.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"计划结束时间不能为空"];
        return;
    }
    
    AppDelegate *mydelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    NSArray *allPileArray = mydelegate.PirArray;
    NSMutableArray *drawArray = [[NSMutableArray alloc] init];
    for (PileInfo *model in allPileArray) {
        if ([model.RoadUID isEqualToString:_currentRoadModel.RoadUID]) {     // 主干道
            [drawArray addObject:model];
        }
    }
    
    if ([self.beginPileNOV.midTextField.text integerValue] > drawArray.count) {
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"桩号不能大于%ld",(unsigned long)drawArray.count]];
        return;
    }
    
    if (self.beginPileNOV.midTextField.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"开始桩号不能为空"];
        return;
    }
    
    if (self.endPileNOV.midTextField.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"结束桩号不能为空"];
        return;
    }
    
    if ([self.endPileNOV.midTextField.text integerValue] > drawArray.count) {
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"桩号不能大于%ld",(unsigned long)drawArray.count]];
        return;
    }
    
    if ([self.beginPileNOV.midTextField.text integerValue] > [self.endPileNOV.midTextField.text integerValue]) {
        [SVProgressHUD showErrorWithStatus:@"开始桩号不能大于结束桩号"];
        return;
    }
    
//    if (self.postionV.middelBtn.currentTitle) {
////        NSLog(@"%@",self.postionV.middelBtn.currentTitle);
//        [SVProgressHUD showErrorWithStatus:@"施工地点不能为空"];
//        return;
//    }
    
    if (self.postionV.rightBtn.currentTitle.length ) {
        [SVProgressHUD showErrorWithStatus:@"是否为主线不能为空"];
        return;
    }
    
 //   if (self.vehicleDirectionV.chooseDirectBtn.currentTitle.length < 1) {
//        [SVProgressHUD showErrorWithStatus:@"行车方向不能为空"];
  //      return;
   // }
    
    if (self.constructProjectV.desTextV.text.length < 1) {
        [SVProgressHUD showErrorWithStatus:@"施工内容不能为空"];
        return;
    }
    
    if (!(self.constructDesV.desTextV.text.length > 0))  {
        [SVProgressHUD showErrorWithStatus:@"施工处置不能为空"];
        return;
    }
    [self postDataToServer];
}
//
- (void) postDataToServer {
    [SVProgressHUD showWithStatus:@"正在上报中..."];
    RequestGinsengModel *RequestGinseng=[[RequestGinsengModel alloc] init];
    RequestGinseng.URL         = GetEventDataURL;
    RequestGinseng.DataValue   = [self dataValueString];
    RequestGinseng.UpdatedTime = @"2012-01-12 12:00:00";
    RequestGinseng.SystemCode  = @"GuangleHighway";
    RequestGinseng.MethodName  = @"ReportConstructionEventDetailInfo";
    
    NSDictionary *dic=[[NSDictionary alloc] init];
    dic = @{@"methodName":RequestGinseng.MethodName,@"updatedtime":RequestGinseng.UpdatedTime,@"systemcode":DefaultSystemCode,@"DataValue":RequestGinseng.DataValue};
    
    [BCNetAPIClient PostVideosAndImages:GetEventDataURL parameters:dic imageArray:self.selectPhoteArray videoArray:_videoUrl.absoluteString success:^(id responseObjecet) {
        [SVProgressHUD dismiss];
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSError *error) {
        [SVProgressHUD showSuccessWithStatus:@"上报失败"];
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

- (NSString *)dataValueString {
//    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    ConstructionEventDetailInfo *eventInfo = [[ConstructionEventDetailInfo alloc] init];
    
    eventInfo.Department        = self.constructV.desTextV.text;
    eventInfo.Header            = self.personInChargeV.desTextV.text;
    eventInfo.Telephone         = self.contacterV.desTextV.text;
    eventInfo.Content           = self.constructProjectV.desTextV.text;
    
    EventBaseInfo *baseModel     = [[EventBaseInfo alloc] init];
    NSString *kStr = [NSString stringWithFormat:@"K"];
    
    NSString *bStr               = [kStr stringByAppendingString:self.beginPileNOV.midTextField.text];
    baseModel.BeginPile          = bStr;
    baseModel.BeginPileDistance  = [self.beginPileNOV.rightTextField.text integerValue];
    
    NSString *eStr = [kStr stringByAppendingString:self.endPileNOV.midTextField.text];
    baseModel.EndPile            = eStr;
    baseModel.EndPileDistance    = [self.endPileNOV.rightTextField.text integerValue];
    
    baseModel.IncidentSource     = @"2";
    baseModel.OccurTime          = self.planBeginTimeV.timeChooseBtn.currentTitle;
    baseModel.EndTime            = self.planEndTimeV.timeChooseBtn.currentTitle;
    baseModel.IncidentType       = @"3";
    baseModel.IncidentParentType = @"3";
    baseModel.IncidentUID        = _reportModel.IncidentUID;
    baseModel.UpdateUserName     = _Model.EventBaseInfo.UpdateUserName;
  //  NSLog(@"%@",self.vehicleDirectionV.directionLabel.text);
    baseModel.RoadDerectionName  = self.vehicleDirectionV.directionLabel.text;
    baseModel.RoadDerection      =[NSString stringWithFormat:@"%ld",(long)_roadIndex];
    
    if ([self.postionV.middelBtn.currentTitle isEqualToString:@"收费站"]) {
        baseModel.TollStationUID    = _stationModel.TollStationUID;
        baseModel.TollStationName   = self.postionV.rightBtn.currentTitle;
        baseModel.RoadUID           = _currentRoadModel.RoadUID;
        baseModel.RoadDerectionName = self.vehicleDirectionV.directionLabel.text;
        //NSLog(@"%@",_RoadDirectionTF.text);
        //NSInteger roadIndex         = [_roadDirectionArray indexOfObject:self.vehicleDirectionV.chooseDirectBtn.currentTitle];
       // baseModel.RoadDerection     = [NSString stringWithFormat:@"%d",(int)roadIndex + 1];
        
        baseModel.Latitude  = _stationModel.Latitude;
        baseModel.Longitude = _stationModel.Longitude;
    }else {
        
        baseModel.RoadUID           = _currentRoadModel.RoadUID;
        baseModel.RoadDerectionName = self.vehicleDirectionV.directionLabel.text;
     //   NSInteger roadD             = [_roadDirectionArray indexOfObject:baseModel.RoadDerectionName];
      //  baseModel.RoadDerection     = [NSString stringWithFormat:@"%d",(int)roadD + 1];
        baseModel.TollStationName = nil;
        baseModel.TollStationUID  = nil;
        AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        for (PileInfo *modelPile in myDelegate.PirArray) {
            //    NSLog(@"%@ %@ %@ %@",modelPile.PileNo, modelPile.RoadUID , info.EventBaseInfo.RoadUID, info.EventBaseInfo.BeginPile);
            NSString *infoRoad = baseModel.RoadUID;
            NSString *infoPile = baseModel.BeginPile;
            NSString *pileRoad = modelPile.RoadUID;
            NSString *pileNO   = modelPile.PileNo;
            if ([infoRoad isEqualToString:pileRoad] && [infoPile isEqualToString:pileNO] ) {
                baseModel.Latitude  = modelPile.Latitude;
                baseModel.Longitude = modelPile.Longitude;
            }
        }
    }
    
    for (HighWayRoadRecordDirectionInfoModel *model in _currentRoadModel.highWayRoadDirectionList) {
        if ([model.DirectionDescription isEqualToString:baseModel.RoadDerectionName]) {
             baseModel.RoadDerection     = model.RoadDirection;
        }
    }
    
    NSDate *now = [RODateHelper localeDate];
    NSString *dateStr = [RODateHelper dateToString:now withFormat:nil];
    baseModel.UpdateTime         = dateStr;
    //    baseModel.RoadDerection      = [NSString stringWithFormat:@"%ld",(long)_roadIndex];
    //    baseModel.RoadName           = _mainLineTF.text;
    baseModel.ETCExitCount       = _Model.EventBaseInfo.ETCExitCount;
    NSLog(@"%@  %@",self.vehicleDirectionV.chooseDirectBtn.currentTitle, self.vehicleDirectionV.chooseDirectBtn.titleLabel.text);
    baseModel.RoadDerectionName  = self.vehicleDirectionV.directionLabel.text;
    baseModel.IncidentSource     = [NSString stringWithFormat:@"%d",2];
    baseModel.IncidentDetail     = self.constructDesV.desTextV.text;
    baseModel.DealDetail         = self.constructDesV.desTextV.text;
    baseModel.RoadUID            = _currentRoadModel.RoadUID;
    baseModel.ETCExitCount       = _Model.EventBaseInfo.ETCExitCount;
    baseModel.SystemUID          = _Model.EventBaseInfo.SystemUID;
    baseModel.State              = _Model.EventBaseInfo.State;
    baseModel.IncidentLevel      = _Model.EventBaseInfo.IncidentLevel;
    baseModel.RecordUserUID      = _Model.EventBaseInfo.RecordUserUID;
    baseModel.RecordUserName     = _Model.EventBaseInfo.RecordUserName;
    baseModel.ActualEndTime      = nil;
    baseModel.RecordTime         = _Model.EventBaseInfo.RecordTime;
    baseModel.SystemCode         = _Model.EventBaseInfo.SystemCode;
    baseModel.IncidentTypeName   = _Model.EventBaseInfo.IncidentTypeName;
    baseModel.IncidentDetail     = self.constructDesV.desTextV.text;
    eventInfo.EventBaseInfo      = baseModel;
//NSLog(@"%@ %@",baseModel.RoadDerectionName, _RoadDirectionTF.text);
    
    EventDealList *listModel = [[EventDealList alloc] init];
    listModel.DealDetail     = self.constructDesV.desTextV.text;
    listModel.IncidentUID    = _reportModel.IncidentUID;
    listModel.DealTime       = dateStr;
    eventInfo.EventDealList  = @[listModel];
    
    NSMutableDictionary *dic = eventInfo.mj_keyValues;
    NSString *json           = [dic mj_JSONString];
    
    ParModel *model = [[ParModel alloc] init];
    model.key       = @"ConstructionEventDetailInfo";
    model.value     = json;
    
    NSMutableDictionary *ModelDic = model.mj_keyValues;
    NSString *dataValue  = [ModelDic mj_JSONString];
    NSString *str        = @"[";
    NSString *temp       = [str stringByAppendingString:dataValue];
    NSString *str1       = @"]";
    NSString *JsonString = [temp stringByAppendingString:str1];
    //NSLog(@"Jsonstring%@",JsonString);
    return JsonString;
}

- (void) cancleBtnClick {
    UIAlertView *showAlert=[[UIAlertView alloc] initWithTitle:nil message:@"是否确认结束该事件" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [showAlert show];
}
#pragma mark - AlertViewDelegate  (点击结束按钮)
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        [alertView dismissWithClickedButtonIndex:0 animated:YES];
    }
    if (buttonIndex == 1) {
        [self cancleTheEvent];
    }
}

#pragma mark - 提交取消事件
- (void) cancleTheEvent {
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *CancleConstructionEventDetailInfoModel =[[RequestGinsengModel alloc] init];
    CancleConstructionEventDetailInfoModel.URL         = GetEventDataURL;
    CancleConstructionEventDetailInfoModel.MethodName  = @"StopOrCancelConstructionEvent";
    CancleConstructionEventDetailInfoModel.DataValue   = [self cancleConstructDataValueStr:self.reportModel.IncidentUID];
    CancleConstructionEventDetailInfoModel.UpdatedTime = @"";
    CancleConstructionEventDetailInfoModel.SystemCode  = @"GuangleHighway";
    requestHelper.block = ^(RequestOutginseng *requestOutginseng,id dataValueModel){
        if([requestOutginseng.Message isEqualToString:@"请求成功"]){
            [SVProgressHUD showSuccessWithStatus:@"成功取消事件"];
        }
        [self.navigationController popViewControllerAnimated:YES];
        
    };
    [requestHelper RequestGinsengModel:CancleConstructionEventDetailInfoModel andPushController:self];
}
-(NSString *)cancleConstructDataValueStr:(NSString *)IncidentUID {
    NSString *valueStr =[NSString stringWithFormat:@"[{\"key\":\"IncidentUID\",\"value\":\"%@\"}]",IncidentUID];
    return valueStr;
}

#pragma mark -  图片和视频按钮点击
- (void) videoBtnClick {
    LittleVideoViewController *vc = [[LittleVideoViewController alloc] init];
    vc.delegate = self;
    [self.navigationController presentViewController:vc animated:YES completion:nil];
}

- (void) photoesBtnClick {
    if (self.selectPhoteArray.count >= 5) {
        [SVProgressHUD showErrorWithStatus:@"不能选择超过5张图"];
        return;
    }
    AJPhotoPickerViewController *picker = [[AJPhotoPickerViewController alloc] init];
    picker.maximumNumberOfSelection = 5 - self.selectPhoteArray.count;
    picker.multipleSelection        = YES;
    picker.assetsFilter             = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups          = YES;
    picker.delegate                 = self;
    picker.selectionFilter          = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        return YES;
    }];
    
    [self presentViewController:picker animated:YES completion:nil];
}
#pragma mark- init
- (void) setUpArray {
    _selectPhoteArray = [[NSMutableArray alloc] init];
    _lineArray       = [[NSMutableArray alloc] init];
    _isMainLineArray = [[NSArray alloc] init];
    _roadDirectionArray = [[NSMutableArray alloc] init];
    _stationArray   = [[NSMutableArray alloc] init];
}
#pragma mark - request
- (void) requestData {
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *GetConstructionEventDetailInfo = [[RequestGinsengModel alloc] init];
    GetConstructionEventDetailInfo.URL         = GetEventDataURL;
    GetConstructionEventDetailInfo.DataValue   = [self getConstructDataValueStr:self.reportModel.IncidentUID];
    GetConstructionEventDetailInfo.UpdatedTime = @"";
    GetConstructionEventDetailInfo.SystemCode  = @"GuangleHighway";
    GetConstructionEventDetailInfo.MethodName  = @"GetConstructionEventDetailInfo";
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        _Model = [EventDetailModel mj_objectWithKeyValues:requestOutginseng.DataValue];
        [self getCurrentHighWayRoadModel];
        [self refreshUIData];
        [self.containerV layoutSubviews];
        [self.wrapperView layoutSubviews];
        [self configRoadIndex];
//        [self configRoadIndex];
    };
    [requestHelper RequestGinsengModel:GetConstructionEventDetailInfo andPushController:self];
}
-(NSString *)getConstructDataValueStr:(NSString *)IncidentUID {
    NSString *valueStr =[NSString stringWithFormat:@"[{\"key\":\"EventUID\",\"value\":\"%@\"}]",IncidentUID];
    return valueStr;
}

- (void) getCurrentHighWayRoadModel { //获取返回来的道路模型
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    for (HighwayMergeRoadRecordModel *roadModel in myDelegate.HighWayRoadArray) {
        if ([roadModel.RoadUID isEqualToString:_Model.EventBaseInfo.RoadUID]) {
            _currentRoadModel = roadModel;
        }
    }
}
- (void) configRoadIndex {
    for (HighWayRoadRecordDirectionInfoModel *model in _currentRoadModel.highWayRoadDirectionList) {
        if ([self.vehicleDirectionV.chooseDirectBtn.currentTitle isEqualToString:model.DirectionDescription]) {
            NSInteger ind = [_roadDirectionArray indexOfObject:model.DirectionDescription];
            _roadIndex = ind + 1;
        }
    }
}
#pragma mark - 刷新数据
- (void) refreshUIData {
    [self.constructV      setContentString:_Model.Department] ;
    [self.personInChargeV setContentString:_Model.Header];
    [self.contacterV      setContentString:_Model.Telephone]  ;
    [self.planBeginTimeV  setTimeString:_Model.EventBaseInfo.OccurTime];
    [self.planEndTimeV    setTimeString:_Model.EventBaseInfo.EndTime];
    [self.vehicleDirectionV setContentString:_Model.EventBaseInfo.RoadDerectionName];
    
    if (_Model.EventBaseInfo.TollStationName.length > 0) {
        [self.postionV setMiddelString:@"收费站" rightString:_Model.EventBaseInfo.TollStationName];
    }else {
        NSString *isRampStr = _Model.EventBaseInfo.IsRamp ? @"非主线" : @"主线";
        
        [self.postionV setMiddelString:_Model.EventBaseInfo.RoadName rightString:isRampStr];
    }
    // 桩号
    NSString *b                 = [NSString stringWithFormat:@"%@",_Model.EventBaseInfo.BeginPile];
    NSString *begin             = [b substringWithRange:NSMakeRange(1, b.length - 1)];
//    NSLog(@"-%@",begin);
    NSString *beginDistance     = [NSString stringWithFormat:@"%ld",(long)_Model.EventBaseInfo.BeginPileDistance];
    NSString *bd                = [NSString stringWithFormat:@"%@",_Model.EventBaseInfo.EndPile];
    NSString *end               = [bd substringWithRange:NSMakeRange(1, bd.length - 1)];
    NSString *endDistance       = [NSString stringWithFormat:@"%ld",(long)_Model.EventBaseInfo.EndPileDistance];
  //  if ([_Model.EventBaseInfo.RoadUID isEqualToString:@"8dd13d88-cb02-4471-876b-1dfe39419ee6"]) {
        NSString *kBeginStr = [NSString stringWithFormat:@"%@",begin];
        [self.beginPileNOV setMiddelString:kBeginStr rightString:beginDistance];
        
        NSString *kEndStr = [NSString stringWithFormat:@"%@",end];
        [self.endPileNOV setMiddelString:kEndStr rightString:endDistance];
        
  //  } else {
    //    NSString *lkBeginStr = [NSString stringWithFormat:@"LK %@",begin];
    //    [self.beginPileNOV setMiddelString:lkBeginStr rightString:beginDistance];
        
    //    NSString *lkEndStr = [NSString stringWithFormat:@"LK %@",end];
    //    [self.endPileNOV setMiddelString:lkEndStr rightString:endDistance];
   // }
    [self setKOrLKLabel];
    [self.constructProjectV setContentString:_Model.Content];
}
#pragma mark - BoPhotoPickerProtocol
- (void)photoPickerDidCancel:(AJPhotoPickerViewController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)photoPicker:(AJPhotoPickerViewController *)picker didSelectAssets:(NSArray *)assets {
    if ((self.selectPhoteArray.count + assets.count) > 5)  {
        [SVProgressHUD showSuccessWithStatus:@"不能超过5张"];
        return;
    }
    [picker dismissViewControllerAnimated:NO completion:nil];
    for (int i = 0; i < assets.count; i ++) {
        ALAsset *asset =  assets[i];
        UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        [self.selectPhoteArray addObject:tempImg];
    }
    [self reConfigPhotoesView];
}

- (void) reConfigPhotoesView {
    for (UIImageView *imgV in self.photoesV.scrollV.subviews) {
        [imgV removeFromSuperview];
    }
    CGFloat x = 5;
    CGRect frame = CGRectMake(0, 0, 100, 100);
    
    self.photoesV.scrollV.contentSize = CGSizeMake(105 * self.selectPhoteArray.count + 5, 0);
    for (int i = 0 ; i < self.selectPhoteArray.count; i++) {
        frame.origin.x = x;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
        [imageView setContentMode:UIViewContentModeScaleAspectFill];
        imageView.clipsToBounds          = YES;
        imageView.image                  = self.selectPhoteArray[i];
        imageView.tag                    = i;
        imageView.userInteractionEnabled = YES;
        [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showBig:)]];
        [self.photoesV.scrollV addSubview:imageView];
        
        x += frame.size.width+5;
    }
    [self.containerV setupAutoHeightWithBottomView:self.photoesV bottomMargin:10];
    [self.containerV layoutSubviews];
}

- (void)showBig:(UITapGestureRecognizer *)sender {
    NSInteger index = sender.view.tag;
    AJPhotoBrowserViewController *photoBrowserViewController = [[AJPhotoBrowserViewController alloc] initWithPhotos:self.selectPhoteArray index:index];
    photoBrowserViewController.delegate = self;
    //    UIImage *img = self.selectPhoteArray[index];
    [self.selectPhoteArray removeObjectAtIndex:index];
    
    [self presentViewController:photoBrowserViewController animated:YES completion:nil];
    
}
- (void)photoBrowser:(AJPhotoBrowserViewController *)vc didDonePhotos:(NSArray *)photos {
    [vc dismissViewControllerAnimated:YES completion:nil];
    [self reConfigPhotoesView];
}

- (void)photoPickerTapCameraAction:(AJPhotoPickerViewController *)picker {
    [self checkCameraAvailability:^(BOOL auth) {
        if (!auth) {
            NSLog(@"没有访问相机权限");
            return;
        }
        [picker dismissViewControllerAnimated:NO completion:nil];
        UIImagePickerController *cameraUI = [UIImagePickerController new];
        cameraUI.allowsEditing   = NO;
        cameraUI.delegate        = self;
        cameraUI.sourceType      = UIImagePickerControllerSourceTypeCamera;
        cameraUI.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
        [self presentViewController: cameraUI animated: YES completion:nil];
    }];
}
- (void)checkCameraAvailability:(void (^)(BOOL auth))block {
    BOOL status = NO;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == AVAuthorizationStatusAuthorized) {
        status = YES;
    } else if (authStatus == AVAuthorizationStatusDenied) {
        status = NO;
    } else if (authStatus == AVAuthorizationStatusRestricted) {
        status = NO;
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(granted){
                if (block) {
                    block(granted);
                }
            } else {
                if (block) {
                    block(granted);
                }
            }
        }];
        return;
    }
    if (block) {
        block(status);
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *originalImage;
    if (CFStringCompare((CFStringRef) mediaType,kUTTypeImage, 0)== kCFCompareEqualTo) {
        originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImageWriteToSavedPhotosAlbum(originalImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo {
    if (!error) {
        //        NSLog(@"保存到相册成功");
        AJPhotoPickerViewController *picker = [[AJPhotoPickerViewController alloc] init];
        picker.maximumNumberOfSelection = 5;
        picker.multipleSelection        = YES;
        picker.assetsFilter             = [ALAssetsFilter allPhotos];
        picker.showEmptyGroups          = YES;
        picker.delegate                 = self;
        picker.selectionFilter          = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            return YES;
        }];
        [self dismissViewControllerAnimated:NO completion:nil];
        [self presentViewController:picker animated:NO completion:nil];
    }else{
        //        NSLog(@"保存到相册出错%@", error);
    }
}
// *********** - 播放小视频 - *************
#pragma mark -littleVideoDelegate
- (void)finishLittleVideoViewControllerCapture:(NSURL *)filePath {
    _videoUrl = filePath;
    UIView *view;
    if (self.selectPhoteArray.count > 0) {
        view = self.photoesV;
    }else {
        view = self.constructDesV;
    }
    
    if (_videoUrl) {
        self.videoView.sd_layout
        .widthIs([UIScreen mainScreen].bounds.size.width - 20)
        .heightEqualToWidth(0)
        .topSpaceToView(view, 10)
        .centerXEqualToView(self.containerV)
        ;
        [self.containerV setupAutoHeightWithBottomView:self.videoView bottomMargin:10];
        [self.containerV layoutSubviews];
    }
    
    [self crreatPlayViedeo:filePath];
    
}
- (void) crreatPlayViedeo:(NSURL *)videoUrl {
    _playItem = [AVPlayerItem playerItemWithURL:videoUrl];
    _player = [AVPlayer playerWithPlayerItem:_playItem];
    _playerLayer =[AVPlayerLayer playerLayerWithPlayer:_player];
    _playerLayer.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width - 16, 200);
    _playerLayer.videoGravity=AVLayerVideoGravityResizeAspectFill;//视频填充模式
    [self.videoView.layer addSublayer:_playerLayer];
    [_player play];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_player pause];
    _player = nil;
}

-(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
    return UIModalPresentationNone;
}


@end
